<?php
/*
Plugin Name: Smowtion
Plugin URI: http://smowtion.com
Description: Smowtion Media WordPress Plugin
Version: 0.4
Author: Marcos Sader
Author URI: http://fenix.st
	
	Copyright 2008 - Smowtion Media

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if ( ! class_exists('Smowtion') ) :

class Smowtion
{
	var $db;
	var $section			= false;
	var $ads				= array();
	var $installed			= false;
	var $table_name;	
	var $options;
	var $disabled_options	= array();
	var $wp_admin_url;
	var $plugin_page;
	var $plugin_url;
	var $ad_tpl		=	"\n<!-- BEGIN SMOWTION -->\n
						<div class='smowtionAd' style='%s' id='smowtionAd%d'>\n
						%s\n
						<script type='text/javascript'>\n
						<!--\n
						smowtion_size = '%s';\n
						smowtion_section = '%d';\n
						//-->\n
						</script>\n
						<script type='text/javascript' src='http://ads.smowtion.com/ad.js'></script>\n
						%s\n
						</div>\n
						<!-- END SMOWTION TAG -->\n";	
	
	function Smowtion()
	{
		global $wpdb;
				
		$this->db =& $wpdb; //$wpdb reference
		$this->table_name	= $this->db->prefix . 'smowtion_ads';
		$this->section		= get_option('smowtion_section');
		$this->installed	= (bool) $this->section;
		
		register_activation_hook( __FILE__, array(&$this, 'activate'));
		register_deactivation_hook( __FILE__, array(&$this, 'deactivate'));
		
		add_action('admin_menu', array(&$this, 'addAmdinPages'));
		add_action('the_content', array(&$this, 'contentFilter'));		
				
		wp_enqueue_script('admin-forms');		
		
		$this->setOptions();
		$this->wp_admin_url = get_option('siteurl') . '/wp-admin/admin.php';
		$this->plugin_page	= plugin_basename(__FILE__);
		$this->plugin_url	= $this->wp_admin_url . '?page=' . $this->plugin_page;
		
		if (!$this->isDbInstalled())
			$this->dbInstall();
			
	}
	
	function __construct()
	{
		$this->Smowtion();
	}
	
	/*
	--------------------------
	INSTALL/UNINSTALL
	--------------------------
	*/
	
	function activate()
	{
		if ( ! get_option('smowtion_section') )
			add_option('smowtion_section', false, '', 'yes');
		
		if ( ! $this->isDbInstalled() )
			$this->dbInstall();
	}
	
	function isDbInstalled()
	{
		return ($this->db->query($this->db->prepare("SHOW TABLES LIKE '%s';", $this->table_name))) ? true : false;
	}
	
	function dbInstall()
	{
		$sql = "CREATE TABLE `{$this->table_name}` (
			`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
			`name` VARCHAR(20) NULL,
			`format` VARCHAR(10) NOT NULL,
			`location` VARCHAR(20) NOT NULL,
			`align` VARCHAR(10) NOT NULL,
			`before` VARCHAR(255) NULL,
			`after` VARCHAR(255) NULL,
			`olderthan` INT NOT NULL DEFAULT '0'
		);";
		require_once(ABSPATH . 'wp-admin' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'upgrade.php');
		return dbDelta($sql);
	}
	
	function deactivate(){}
	
	/*
	--------------------------
	SMOWTION OPTIONS
	--------------------------
	*/
	
	function setOptions()
	{
		$day = 60*60*24;
		$this->options = array();
		$this->options['format'] = array(
			'120x600'	=> '120x600',
			'300x250'	=> '300x250',
			'468x60'	=> '468x60',
			'728x90'	=> '728x90',
			'160x600'	=> '160x600',
			'234x60'	=> '234x60'
		);
		$this->options['location'] = array(
			'custom'		=> 'Libre',
			'widget'		=> 'Widget',
			'post_top'		=> 'Post - Arriba',
			'post_bottom'	=> 'Post - Abajo'
		);
		$this->options['align'] = array(
			'left'	=> 'Izquierda',
			'center'=> 'Centro',
			'right'	=> 'Derecha'
		);
		$this->options['olderthan'] = array(
			0		=> 'Inmediata',
			$day	=> '1 día',
			$day*7	=> '1 semana',
			$day*14	=> '2 semanas',
			$day*21	=> '3 semanas',
			$day*30	=> '1 mes'
		);
	}
	
	function getOptionsSelect($options, $name, $active=false)
	{
		if ( count($this->disabled_options) > 0 ) :
			foreach($this->disabled_options as $k) :
				unset($options[$k]);
			endforeach;
		endif;
				
		$html = '<select name="' . $name . '" id="' . $name . '">'."\n";
		foreach ($options as $k=>$v) :
			$selected = ($active == $k) ? 'selected="selected"' : '';
			$html .= '<option '. $selected .' value="' . $k . '">' . $v . "</option>\n";
		endforeach;
		$html .= '</select>';
		return $html;
	}
	
	function setDisabledOptions($action='update', $id=0){
		$top	= $this->getAdByLocation('post_top');
		$bottom = $this->getAdByLocation('post_bottom');
		$widget = $this->getAdByLocation('widget');

		switch ($action) :
			case 'update' :
				if($top && ($top->id != $id))
					$this->disabled_options[] = 'post_top';	
				if($bottom && ($bottom->id != $id))
					$this->disabled_options[] = 'post_bottom';
				if($widget && ($widget->id != $id))
					$this->disabled_options[] = 'widget';
				break;
			case 'new' :
				if($top)
					$this->disabled_options[] = 'post_top';
				if($bottom)
					$this->disabled_options[] = 'post_bottom';
				if($widget)
					$this->disabled_options[] = 'widget';
				break;
		endswitch;
	}		
	
	
	/*
	--------------------------
	ADS
	--------------------------
	*/	
	
	function buildAd($ad)
	{
		$style = ($ad->align == 'left' || $ad->align == 'right') ? "float:{$ad->align};" : "text-align:center;";
		return sprintf($this->ad_tpl, $style, $ad->id, $ad->before, $ad->format, $this->section, $ad->after);
	}	
	
	function getAdById($id=0)
	{
		$ad = $this->db->get_row($this->db->prepare("SELECT * FROM {$this->table_name} WHERE id = %d", intval($id)));
		return ($ad) ? sprintf($this->ad_tpl, $ad->before, $ad->format, $this->section, $ad->after) : false;
	}
	
	function getAdByLocation($location='custom')
	{
		return $this->db->get_row($this->db->prepare("SELECT * FROM {$this->table_name} WHERE location = '%s'", $location));
	}
	
	
	/*
	--------------------------
	CONTENT FILTER
	--------------------------
	*/
	
	function contentFilter($content)
	{
		global $post;
		$post_time		= get_the_time('U');
		$post_top		= '';
		$post_bottom	= '';
		$ad_top			= $this->getAdByLocation('post_top');
		$ad_bottom		= $this->getAdByLocation('post_bottom');
		
		if ($ad_top) :
			$pub_time = $post_time + $ad_top->olderthan;
			if ($pub_time <= time())
				$post_top .= $this->buildAd($ad_top);
		endif;
		
		if ($ad_bottom) :
			$pub_time = $post_time + $ad_bottom->olderthan;
			if ($pub_time <= time())
				$post_bottom .= $this->buildAd($ad_bottom);
		endif;
		
		return $post_top . $content . $post_bottom;
	}
	
	
	/*
	--------------------------
	ADMIN PAGES
	--------------------------
	*/
	
	function addAmdinPages()
	{
		add_menu_page('Smowtion', 'Smowtion', 9, __FILE__, array(&$this, 'showManagePage'));
		add_submenu_page(__FILE__, 'Smowtion &raquo; Administrar Anuncios', 'Administrar Anuncios', 9, __FILE__, array(&$this, 'showManagePage'));
		add_submenu_page(__FILE__, 'Smowtion &raquo; Configuración', 'Configuración', 9, 'smowtion_options', array(&$this, 'showOptionsPage'));		
	}		

	function showOptionsPage()
	{
		if (isset($_POST['smowtion_section'])) :
			preg_match('([0-9]{6})', htmlentities($_POST['smowtion_section']), $matches);
			$smowtion_section = (isset($matches[0])) ? $matches[0] : NULL;
			update_option('smowtion_section', $smowtion_section);
		endif;
		$this->section = get_option('smowtion_section'); //refresh
		include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'options.php';
	}
	
	function showManagePage()	
	{
		if(isset($_GET['smowtion_ad_id'])) : // display update form
			$this->updateAd(intval($_GET['smowtion_ad_id']));
		else :
		
			$deletes = (isset($_POST['delete'])) ? $_POST['delete'] : false;
			if ( $deletes && count($deletes) > 0 ) :
				foreach ($deletes as $id) :
					$this->db->query(sprintf("DELETE FROM {$this->table_name} WHERE id = '%d' LIMIT 1",intval($id)));
				endforeach;
			endif;
			
			$data = (isset($_POST['newad'])) ? $_POST['newad'] : false;
			if ( $data && count($data) > 0 ) :
				$this->db->query(
					$this->db->prepare(
						"INSERT INTO {$this->table_name} VALUES (NULL, %s, %s, %s, %s, %s, %s, %d)",
						$data['name'], $data['format'], $data['location'], $data['align'], stripcslashes($data['before']), stripcslashes($data['after']), $data['olderthan']
					)
				);
			endif;
			
			$this->ads = $this->db->get_results("SELECT * FROM {$this->table_name}");
			$this->setDisabledOptions('new');
			
			include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'manage.php';
			
		endif;
	}
	
	function updateAd($id=0)
	{
		$data = (isset($_POST['ad'])) ? $_POST['ad'] : false;
		if ( $data && count($data) > 0 ) :
			$this->db->query(
				$this->db->prepare(
					"UPDATE {$this->table_name} SET name = %s, format = %s, location = %s, align = %s, `before` = %s, `after` = %s, olderthan = %d WHERE id = %d LIMIT 1;",
					$data['name'], $data['format'], $data['location'], $data['align'], stripcslashes($data['before']), stripcslashes($data['after']), $data['olderthan'], $data['id']
				)
			);
		endif;
		
		$ad = $this->db->get_row($this->db->prepare("SELECT * FROM {$this->table_name} WHERE id = %d", intval($id)));
		$this->setDisabledOptions('update', intval($id));		
			
		include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'update.php';
	}
	
	/*
	--------------------------
	UTILITIES
	--------------------------
	*/	
	
	function showStatus()
	{		
		if ( ! isset($_POST['submit']) ) :
			if ( ! $this->installed ) :
				function msg()
				{
					$url = get_option('siteurl') . '/wp-admin/admin.php?page=smowtion_options';
					echo sprintf('<div id="smowtion_notice" class="updated fade"><p><strong>Smowtion está casi listo</strong>, falta ingresar el <a href="%s">smowtion_section</a></p></div>', $url);
				}
				add_action('admin_notices', 'msg'); //WP add_action sucks.
			endif;			
		endif;
	}
	
}
endif; //CLASS EXISTS

/*
--------------------------
SMOWTIONIZE
--------------------------
*/
$smowtion = new Smowtion();
$smowtion->showStatus();

/*
--------------------------
HELPER
--------------------------
*/
function showSmotionAd($id=0){
	global $smowtion;
	echo $smowtion->getAdById(intval($id));
}

/*
--------------------------
WIDGET
--------------------------
*/

function showSmotionWidget()
{
	if ( !function_exists('register_sidebar_widget') )
		return;		
	function smowtionWidget($args) {
		global $smowtion;
		extract($args);
		echo $before_widget;		
		echo ($ad = $smowtion->getAdByLocation('widget')) ? $smowtion->buildAd($ad) : '<p>No se ha definido un anuncio para ser utilizado en el widget.</p>';
		echo $after_widget;
	}				
	register_sidebar_widget(array('Smowtion Widget', 'widgets'), 'smowtionWidget');
}
add_action('widgets_init', 'showSmotionWidget');

?>